package com.zzw.mvvm.viewmodels.demo;

import android.annotation.SuppressLint;
import android.util.Log;

import com.zzw.mvvm.ApplicationMine;
import com.zzw.mvvm.base.BaseViewModel;
import com.zzw.mvvm.beans.DemoEntity;
import com.zzw.mvvm.repository.local.AppDataBase;
import com.zzw.mvvm.utils.rxutils.RxUtil;

import androidx.lifecycle.MutableLiveData;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;

public class DataBaseDemoViewModel extends BaseViewModel {
    public MutableLiveData<String> name;

    public MutableLiveData<String> getName() {
        if (name == null) {
            name = new MutableLiveData<>();
        }
        return name;
    }

    public void setName(MutableLiveData<String> name) {
        this.name = name;
    }

    @SuppressLint("CheckResult")
    public void getDataMsg() {

        AppDataBase.getInstance(ApplicationMine.getInstance()).demoDao().findByName("zzw", "12")
                .compose(RxUtil.rxSchedulerHelperBP())
                .subscribe(new Consumer<DemoEntity>() {
                    @Override
                    public void accept(DemoEntity demoEntity) throws Exception {
                        name.setValue(demoEntity.getName());
                    }
                });
    }

    @SuppressLint("CheckResult")
    public void addDataMsg() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                AppDataBase.getInstance(ApplicationMine.getInstance()).demoDao().insertAll(new DemoEntity("zzw", "12"));
                emitter.onNext("s1");
                AppDataBase.getInstance(ApplicationMine.getInstance()).demoDao().insertAll(new DemoEntity("zzw1", "123"));
                emitter.onNext("s2");
                emitter.onComplete();
            }
        }).compose(RxUtil.rxSchedulerHelper())
                .subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Log.i("zzw", "success==" + s);
            }
        });
    }
}
